using System;
using System.Collections.Generic;
using Gtk;
using DaphneTranslator;
using DaphneTranslator.BusinessLogic;
using System.Reflection;

public partial class MainWindow: Gtk.Window
{	
	private List<CultureRecord> _languageList;
	private bool _oDirty;
	
	public MainWindow (): base (Gtk.WindowType.Toplevel)
	{
		Build ();
		_languageList = new List<CultureRecord> ();
		
		this.OpenDirectoryAction1.Activated += OpenDirectory;
		this.SaveContentAction1.Activated += SaveContent;
		this.ExitAction1.Activated += ExitApplication;
		this.AboutAction2.Activated += AboutActionHandled;
		wdgLanguageList.LanguageSelected += HandleLanguageSelected;
		wdgLanguageList.FilenameChangedEvent += HandleFilenameChangedEvent;
		wdgLanguageList.NewCultureEvent += HandleNewCultureEvent;
		wdgLanguageList.ChangeOccuredEvent += HandleChangeOccuredEvent;
		wdgLanguage.ChangeOccuredEvent += HandleChangeOccuredEvent;
		wdgLanguage.NewTextRequestEvent += HandleNewTextRequestEvent;
		_oDirty = false;
	}

	void AboutActionHandled (object sender, EventArgs e)
	{
		AboutDialog dialog = new AboutDialog ();
		
		Assembly asm = Assembly.GetExecutingAssembly ();
		
		dialog.ProgramName = (asm.GetCustomAttributes (
			typeof(AssemblyTitleAttribute), false) [0]
			as AssemblyTitleAttribute).Title;
		
		dialog.Version = asm.GetName ().Version.ToString ();
		
		dialog.Comments = (asm.GetCustomAttributes (
			typeof(AssemblyDescriptionAttribute), false) [0]
			as AssemblyDescriptionAttribute).Description;
		
		dialog.Copyright = (asm.GetCustomAttributes (
			typeof(AssemblyCopyrightAttribute), false) [0]
			as AssemblyCopyrightAttribute).Copyright;
		
		dialog.License = license;
		
		dialog.Authors = authors;
		
				
		dialog.Run ();
		dialog.Destroy ();
		
	}

	void HandleNewTextRequestEvent ()
	{
		if (_languageList == null || _languageList.Count == 0) {
			MessageDialog msg = new MessageDialog (this, DialogFlags.Modal, MessageType.Info,
				                                      ButtonsType.Ok, "Open first the resource directory");
			msg.Title = "Open resources";
			msg.Run ();		
			msg.Destroy ();		
			return;
		}
		
		NewRecordWidget dlg = new NewRecordWidget ();
		dlg.SetLanguages (_languageList);
		ResponseType res = (ResponseType)dlg.Run ();
		if (res == ResponseType.Accept) {
			var dic = dlg.GetData ();
			ProcessAddNewRecord (dic);
			
			wdgLanguage.Refresh ();							
			HandleChangeOccuredEvent ();
		}		
		
		dlg.Destroy ();		
	}
	
	private void ProcessAddNewRecord (Dictionary<string, string> dic)
	{
		foreach (var item in _languageList) {
			LanguageText text = new LanguageText ();
			text.Key = dic [RecordKeys.Key];
			text.ValueXmlKey = dic [RecordKeys.XmlNodeValue];
			text.Value = dic [item.Culture];
			
			//item.Texts.Add (text);
		}
	}

	void HandleChangeOccuredEvent ()
	{
		_oDirty = true;
		
	}

	void SaveContent (object sender, EventArgs e)
	{
		if (_languageList.Count == 0)
			return;
		try {
			LanguageManager mng = new LanguageManager ();
			//mng.Save (_languageList, enumFormatType.Xml, wdgPath.GetPath ());
			_oDirty = false;
		} catch (Exception ex) {
			MessageDialog msg = new MessageDialog (this, DialogFlags.Modal, MessageType.Error,
				                                      ButtonsType.Ok, ex.Message);
			msg.Title = "Error saving file";
			msg.Run ();		
			msg.Destroy ();
		}				
	}

	void HandleNewCultureEvent (CultureRecord list)
	{
		_languageList.Add (list);		
	}

	void HandleFilenameChangedEvent (string sOriginalFilePath, string sNewFileName)
	{
/*		foreach (var item in _languageList) {
			if (item.FilePath == sOriginalFilePath) {
				item.Filename = sNewFileName;
				break;
			}
		}		*/
	}
	
	void HandleLanguageSelected (object sender, EventArgs e)
	{
		UpdateLanguageWidget ();		
	}

	void OpenDirectory (object sender, EventArgs e)
	{
		if(_oDirty == true)
		{
			MessageDialog msg = new MessageDialog(this, DialogFlags.Modal, MessageType.Question,
			                                  ButtonsType.YesNo, 
			                                      "Do you want to save the current content before opening a new language set?");
			msg.Title = "Save before loading";
			ResponseType resMsg = (ResponseType)msg.Run();
			msg.Destroy();
			if(resMsg == ResponseType.Yes)
			{
				SaveContent(this, EventArgs.Empty);
			}						
		}
		
		FileChooserDialog dlg = new FileChooserDialog (
						"Choose language directory",
			this, FileChooserAction.SelectFolder,
			"Cancel", ResponseType.Cancel, "Open", ResponseType.Accept, null);
		dlg.SelectMultiple = false;
		dlg.DestroyWithParent = true;
		dlg.Modal = true;
		ResponseType res = (ResponseType)dlg.Run ();
		string sPath = dlg.Filename;
		dlg.Destroy ();
		if (res == ResponseType.Accept) {
			LoadDocument (sPath);
		}					
	}
	
	private void LoadDocument (string sPath)
	{
	/*	wdgPath.SetPath (sPath);
		LanguageManager mng = new LanguageManager ();
		try {		
			_languageList = mng.Load (sPath, enumFormatType.Xml);	
			if (_languageList.Count > 0) {
				ConfigHelper.Instance ().RegisterDocument (sPath);
				wdgLanguageList.SetLangauges (_languageList);
				wdgLanguageList.PrimaryLanguage = SelectPrimaryLanguage (_languageList);										
				UpdateLanguageWidget ();								
			} else {
				MessageDialog msg = new MessageDialog (this, DialogFlags.Modal, MessageType.Info,
				                                      ButtonsType.Ok, "No language files were found.");
				msg.Run ();		
				msg.Destroy ();
					
			}
		} catch (Exception ex) {
			MessageDialog msg = new MessageDialog (this, DialogFlags.Modal, MessageType.Error,
				                                      ButtonsType.Ok, ex.Message);
			msg.Run ();		
			msg.Destroy ();
		}	*/
	}
	
	private CultureRecord GetLangaugeList (string sCulture)
	{
		foreach (var item in _languageList)
			if (item.Culture == sCulture)
				return item;
		return null;
	}
				
	
	private void UpdateLanguageWidget ()
	{
		string sPrimaryLanguage = wdgLanguageList.PrimaryLanguage;
		string sSelectedLanguage = wdgLanguageList.GetSelectedCulture ();
		if (string.IsNullOrWhiteSpace (sSelectedLanguage) == false) {
			/*Culture primary = GetLangaugeList (sPrimaryLanguage);
			Culture selected = GetLangaugeList (sSelectedLanguage);
			if (primary != null && selected != null)
				wdgLanguage.SetLanguages (primary, selected);*/
			
		}		
	}
	
	private string SelectPrimaryLanguage (List<CultureRecord> list)
	{
		// create culture list
		List<string> lstCultures = new List<string> ();
		foreach (var item in list)
			lstCultures.Add (item.Culture);
		
		/*CultureSelectDialog dlg = new CultureSelectDialog ();
		dlg.SetCulturesToSelect (lstCultures);
		dlg.SetQuestionMessage ("Select please the primary language:");
		dlg.SetButtonCancelVisible (false);		
		ResponseType res = (ResponseType)dlg.Run ();
		string sSelCulture = dlg.GetSelectedCulture ();
		dlg.Destroy ();
		
		return sSelCulture;		*/
		return string.Empty;
	}
	
	void ExitApplication (object sender, EventArgs e)
	{
		Application.Quit ();
	}
	
	
	protected void OnDeleteEvent (object sender, DeleteEventArgs a)
	{
		Application.Quit ();
		a.RetVal = true;
	}
	
	private  string [] authors = new string [] {
		"Viktor Přehnal <prehnal@gmail.com>"
	};
	
	private  string license =
@"Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
""Software""), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.";
}
